import request from 'request';
import {getAll} from './rc';
import downLoadGit from 'download-git-repo';
import {DOWNLOAD} from './constants';

const fetch = async (url) => {
    return new Promise((resolve, reject) => {
        let config = {
            url,
            method: 'get',
            headers: {
                'user-agent': ''
            }
        };
        request(config, (err, response, body) => {
            if(err) {
                reject(err);
            }
            resolve(JSON.parse(body));
        })
    });
};

export const tagList = async (repo) => {
    let config = await getAll();
    let api = `https://api.github.com/repos/${config.registry}/${repo}/tags`;
    return await fetch(api);
};

export const repoList = async () => {
    let config = await getAll();
    console.log('config---', config);
    let api = `https://api.github.com/${config.type}/${config.registry}/repos`;
    console.log('api----', api);
    return await fetch(api);
};

export const download = async (src, dest) => {
    return new Promise((resolve, reject) => {
        downLoadGit(src, dest, (err) => {
            if(err) {
                reject(err);
            }
            resolve();
        })
    });
}
export const downloadLocal = async (project, version) => {
    let config = getAll();
    let api = `${config.registry}/${project}`;
    if (version) {
        api += `#${version}`;
    }
    return await download(api, DOWNLOAD + '/' + project)
}